package com.tql.kingdee.controller;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.CommonEntity;
import com.tql.kingdee.api.KingdeeService;
import com.tql.kingdee.bean.TqlStapPriceBean;
import com.tql.kingdee.event.StapPriceHandlerTriggerEvent;
import com.tql.kingdee.util.CommonUtil;
import com.tql.kingdee.util.TimeUtil;
import com.tql.kingdee.response.*;
import com.tql.kingdee.service.*;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/kingdee")
public class KingdeeApiController {
    @Autowired
    private KingdeeService kingdeeService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private TqlEmpService tqlEmpService;

    @Autowired
    private KingdeeMaterialTransUnitService kingdeeMaterialTransUnitService;

    @Autowired
    private MaterialPurchaseService materialPurchaseService;

    @Autowired
    private MaterialIncaseService materialIncaseService;

    @Autowired
    private MaterialTransferService materialTransferService;
    @Autowired
    private ApplicationContext applicationContext;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @PostMapping("/saveShopDept")
    public void saveShopDept(@RequestBody CommonEntity entity)
    {
        String approveDate=null==entity || StringUtils.isEmpty(entity.getApproveDate())? TimeUtil.getCurrentDate():entity.getApproveDate();
        String pFnumber=null==entity || StringUtils.isEmpty(entity.getPfnumber())?null:entity.getPfnumber();
        CommonResponse<List<OrgResponse>> response=kingdeeService.getKingdeeDept(approveDate,pFnumber);
        if(0==response.getFlag())
        {
            List<OrgResponse> list= response.getData();
            if(null!=list && list.size()>0)
            sysDeptService.saveAllOrg(list, CommonUtil.OrgType_COMPANY_DEPT,pFnumber);
        }
    }

    @PostMapping("/findDeptByParentDeptFnumber")
    public List<CommonEntity> findDeptByParentDeptFnumber(@RequestParam("fnumber")  String fnumber)
    {
        List<CommonEntity> response=kingdeeService.findDeptByParentDeptFnumber(fnumber);
        return response;
    }



    @PostMapping("/saveAllOrg")
    public void saveAllOrg(@RequestParam("approveDate") String approveDate)
    {

        CommonResponse<List<OrgResponse>>  response=kingdeeService.getKingdeeOrgBean(approveDate);
        if(0==response.getFlag())
        {
            List<OrgResponse> list= response.getData();
            if(null!=list && list.size()>0)
                sysDeptService.saveAllOrg(list, CommonUtil.OrgType_COMPANY,null);
        }
    }

    @PostMapping("/saveAllEmp")
    public void saveAllEmp(@RequestParam("approveDate") String approveDate)
    {

       List<com.ruoyi.system.api.domain.EmpResponse>  list=kingdeeService.getAllEmp(approveDate);
            if(null!=list && list.size()>0)
                tqlEmpService.saveEmps(list);

    }


    @GetMapping("/getEmpByIdCard")
    public List<com.ruoyi.system.api.domain.EmpResponse>  getEmpByIdCard(@RequestParam("idcard") String idcard)
    {

        List<com.ruoyi.system.api.domain.EmpResponse>  list=kingdeeService.getEmpByIdCard(null,idcard);
        if(null!=list && list.size()>0)
            tqlEmpService.saveEmps(list);
        return list;

    }



    @PostMapping("/saveMaterialTransUnit")
    public void saveMaterialTransUnit(@RequestParam("approveDate") String approveDate)  {

        List<MaterialTransUnitResponse> list= null;
        try {
            list = kingdeeService.getMaterialTransUnit(approveDate);
            if(null!=list && list.size()>0)
                kingdeeMaterialTransUnitService.batchAdd(list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("KingdeeApiController---saveMaterialTransUnit--approveDate--{}---"+e.getMessage(),approveDate);
        }
    }


    /**
     * 不是集团配送的，各个门店自行采购的单据
     *approveDate 审核时间是哪个月数据就会到哪个月里待着
     */
    @PostMapping("/saveMaterialPurchase")
    public void saveMaterialPurchase(@RequestParam("approveDate") String approveDate)
    {
        List<String> shops= kingdeeService.getEnabledShop();
        List<MaterialPurchaseResponse>  list=kingdeeService.getMaterialPurchase(approveDate,shops);

        if(null!=list && list.size()>0) {
            try {
                List<TqlStapPriceBean> priceHandlerList= getPriceBeanForMaterialPurchaseResponse(list);
                applicationContext.publishEvent(new StapPriceHandlerTriggerEvent(priceHandlerList));
                int month=TimeUtil.getMonth(approveDate,"yyyy-MM-dd");
                materialPurchaseService.batchAdd(list,month);
                materialPurchaseService.batchAddInchange(list,month);
            } catch (ParseException e) {
            e.printStackTrace();
                logger.info("KingdeeApiController----saveMaterialPurchase----approveDate --{}"+e.getMessage(),approveDate);
            }
        }

    }




    /**
     * 这个主要是我们理解的采购
     * 门店采购入库单
     * @param approveDate
     */
    @PostMapping("/saveMaterialIncase")
    public void saveMaterialIncase(@RequestParam("approveDate") String approveDate) throws ParseException {

        List<String> shops= kingdeeService.getEnabledShop();
        List<MaterialIncaseResponse>  list=kingdeeService.getMaterialIncase(approveDate,shops);

        if(null!=list && list.size()>0) {
            try {
                List<TqlStapPriceBean> priceHandlerList= getPriceBeanForMaterialIncaseResponse(list);
                applicationContext.publishEvent(new StapPriceHandlerTriggerEvent(priceHandlerList));
//                materialIncaseService.batchAdd(list,approveDate);
//                public int batchAdd(List<MaterialIncaseResponse> list, String approveDate) throws ParseException {
//
                int month= TimeUtil.getMonth(approveDate,"yyyy-MM-dd");
                int a= materialIncaseService.batchAddIncase(list,month);
                materialIncaseService.batchAddInchange(list,month);

              //  materialIncaseService.batchAddStapPrice(list);
//                applicationContext.publishEvent(new LogEvent(dataLog));


            } catch (ParseException e) {
                e.printStackTrace();
                logger.info("KingdeeApiController----saveMaterialPurchase----approveDate --{}"+e.getMessage(),approveDate);
            }
        }

    }
    private List<TqlStapPriceBean> getPriceBeanForMaterialPurchaseResponse(List<MaterialPurchaseResponse> list) {
        if(CollectionUtils.isEmpty(list))return null;
        List<TqlStapPriceBean> newList=    list.stream().map(e->{
            TqlStapPriceBean tqlStapPrice = new TqlStapPriceBean();
            tqlStapPrice.setStapCode(e.getFMaterialIdfnumber());
            tqlStapPrice.setStapName(e.getFMaterialIdfname());
            tqlStapPrice.setLastPrice(e.getFPrice());
            tqlStapPrice.setPriceUnit(e.getFPriceUnitIDfname());
            tqlStapPrice.setPrice(e.getFPrice());
            //数量
            tqlStapPrice.setLastNum(BigDecimal.valueOf(e.getFRealQty()));
            tqlStapPrice.setWeightedPrice(e.getFPrice());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(e.getFStockIdfnumber()) && !e.getFStockIdfnumber().startsWith("BU")){
                e.setFStockIdfnumber(CommonUtil.deptCodeReplacePrefix(e.getFStockIdfnumber()));
            }
            tqlStapPrice.setDeptCode(e.getFStockIdfnumber());
            return tqlStapPrice;
        }).collect(Collectors.toList());
        return newList;
    }
    private List<TqlStapPriceBean> getPriceBeanForMaterialIncaseResponse(List<MaterialIncaseResponse> list) {
        if(CollectionUtils.isEmpty(list))return null;
    List<TqlStapPriceBean> newList=    list.stream().map(e->{
            TqlStapPriceBean tqlStapPrice = new TqlStapPriceBean();
            tqlStapPrice.setStapCode(e.getFMaterialIdfnumber());
            tqlStapPrice.setStapName(e.getFMaterialIdfname());
            tqlStapPrice.setLastPrice(e.getFPrice());
            tqlStapPrice.setPriceUnit(e.getFPriceUnitIDfname());
            tqlStapPrice.setPrice(e.getFPrice());
            //数量
            tqlStapPrice.setLastNum(BigDecimal.valueOf(e.getFRealQty()));
            tqlStapPrice.setWeightedPrice(e.getFPrice());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(e.getFStockIdfnumber()) && !e.getFStockIdfnumber().startsWith("BU")){
                e.setFStockIdfnumber(CommonUtil.deptCodeReplacePrefix(e.getFStockIdfnumber()));
            }
            tqlStapPrice.setDeptCode(e.getFStockIdfnumber());
            return tqlStapPrice;
        }).collect(Collectors.toList());
    return newList;
    }


    /**
     * 分布式调入单据
     * @param approveDate
     */
    @PostMapping("/saveMaterialTransferin")
    public void saveMaterialTransferin(@RequestParam("approveDate") String approveDate)
    {
        List<String> shops= kingdeeService.getEnabledShop();
        List<MaterialTransferoutResponse>  list=kingdeeService.getMaterialTransferin(approveDate,shops);
        if(null!=list && list.size()>0) {
            try {
                materialTransferService.batchAdd(list,approveDate);

            } catch (ParseException e) {
                e.printStackTrace();
                logger.info("KingdeeApiController----saveMaterialTransferin----approveDate --{}"+e.getMessage(),approveDate);
            }
        }
    }

    /**
     * 分布式调出单据
     * @param approveDate
     */
    @PostMapping("/saveMaterialTransferout")
    public void saveMaterialTransferout(@RequestParam("approveDate") String approveDate) throws ParseException {
        List<String> shops= kingdeeService.getEnabledShop();
        List<MaterialTransferoutResponse>  list=kingdeeService.getMaterialTransferout(approveDate,shops);
        if(null!=list && list.size()>0) {
            materialTransferService.batchAdd(list,approveDate);

        }

    }

    @PostMapping("/init")
    public void init() throws ParseException {
        String approveDate = "2024-02-01";
        int month=TimeUtil.getMonth(approveDate,"yyyy-MM-dd");
        List<String> shops= kingdeeService.getEnabledShop();
        // --------------------------------------------
        List<MaterialPurchaseResponse>  list1=kingdeeService.getMaterialPurchase(approveDate,shops);
        System.out.println("list1"+list1.size());
        if(!list1.isEmpty()) {
            try {
                materialPurchaseService.batchAdd(list1,month);

            } catch (ParseException e) {
                e.printStackTrace();
                logger.info("KingdeeApiController----saveMaterialPurchase----approveDate --{}"+e.getMessage(), approveDate);
            }
        }
        // --------------------------------------------
        List<MaterialTransferoutResponse> list2=kingdeeService.getMaterialTransferin(approveDate,shops);
        System.out.println("list2"+list2.size());
        if(!list2.isEmpty()) {
            try {
                materialTransferService.batchAdd(list2,approveDate);

            } catch (ParseException e) {
                e.printStackTrace();
                logger.info("KingdeeApiController----saveMaterialTransferin----approveDate --{}"+e.getMessage(), approveDate);
            }
        }
        // --------------------------------------------
        List<MaterialTransferoutResponse>  list3=kingdeeService.getMaterialTransferout(approveDate,shops);
        System.out.println("list3"+list3.size());
        if(!list3.isEmpty()) {
            materialTransferService.batchAdd(list3,approveDate);
        }
    }


    @GetMapping("/saveStapByStapcode")
    public void saveStapByStapcode(@RequestParam("stapCode")  String stapCode){

        String approveDate="2023-01-01";
        List<MaterialResponse> list=null;
                CommonResponse<List<MaterialResponse>> response=kingdeeService.getMaterial(approveDate,stapCode);
        if(null!=response && 0==response.getFlag()&& null!=response.getData() && response.getData().size()>0)
        {
             list=   response.getData();
             if(!CollectionUtils.isEmpty(list))
             {
                 MaterialResponse dto= list.get(0);
                 List<MaterialResponse> list1=new ArrayList<>();
                 list1.add(dto);
                 kingdeeMaterialTransUnitService.saveMaterial(list1);
             }



        }

    }















}
